package com.xqboss.apps.service.order.type;

import cn.hutool.core.util.IdUtil;
import com.xqboss.apps.domain.order.OrderItem;
import com.xqboss.apps.domain.order.OrderMain;
import com.xqboss.apps.dto.order.CreateOrderDto;
import com.xqboss.apps.enums.order.OrderStatusEnum;
import com.xqboss.apps.enums.order.RefundStatusEnum;
import com.xqboss.common.core.domain.model.LoginUser;
import com.xqboss.common.utils.SecurityUtils;
import org.springframework.scheduling.annotation.Async;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author Trent
 * @date 2023/8/23
 */
public abstract class OrderTypeExecutor {

    /**
     * 前置检测，
     * 1. 检测商品状态，检测参数
     * 2. 检测订单金额
     */
    protected abstract OrderMain preValidate(CreateOrderDto params);

    /**
     * 锁定库存
     */
    protected abstract void lockStock(Long sourceId, Integer quantity);


    /**
     * 生成订单
     */
    protected OrderMain buildOrder(CreateOrderDto params){
        OrderMain order = new OrderMain();
        //生成订单号
        order.setId(IdUtil.getSnowflakeNextId());
        order.setStatus(OrderStatusEnum.UN_PAY);
        // 买家信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        order.setBuyerUserId(loginUser.getUserId());
        order.setBuyerNick(loginUser.getNickName());
        order.setBuyerMemo(null);
        // 卖家信息
//        order.setSellerUserId();
//        order.setSellerNick();
//        order.setSellerMemo();

        order.setOrderType(params.getOrderType());
        order.setPayType(params.getPayType());
        order.setSkuCnt(params.getQuantity());
        order.setIsInvoice(false);
        order.setIsSettle(false);
        order.setCreateTime(LocalDateTime.now());
        return order;
    }


    // 构建子订单信息
    protected OrderItem buildOrderItem(OrderMain order, CreateOrderDto params){
        OrderItem orderItem = new OrderItem();
        orderItem.setId(IdUtil.getSnowflakeNextId());
        orderItem.setOrderMainId(order.getId());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        orderItem.setUserId(loginUser.getUserId());
        orderItem.setOrderType(params.getOrderType());
        return orderItem;
    }


    /**
     * 创建订单
     * @param params
     * @return
     */
    public OrderMain createOrder(CreateOrderDto params){
        OrderMain orderMain = preValidate(params);
        lockStock(params.getSourceId(), params.getQuantity());
        return orderMain;
    }


    /**
     * 订单支付成功后置处理
     */
    public abstract void orderPayedPost(OrderMain order);

    public void orderCancelPost(OrderMain order){

    }
}
